/**
 * @author:稀饭
 * @time:上午12:00:19
 * @filename:Work.java
 */
package service;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import dao.Video;
import data.DataClass;
import data.PatternString;
import data.Url;

public class Work {
	private static ConnectionWork connectionWork;
	private static ThreadPoolExecutor threadPool = null;
	private static String videoPath = null;
	private static BlockingQueue<Runnable> linkedBlockingQueue = null;
	// 預線程數
	private static int corePoolSize = 5;
	// 開啟的最大線程數
	private static int maximumPoolSize = 10;
	// 空閒線程存活時間
	private static long keepAliveTime = 3;

	public static void main(String[] args) {
		System.out.println("请稍后，程序正在启动。。。。");
		linkedBlockingQueue = new ArrayBlockingQueue<Runnable>(4);
		threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
				keepAliveTime, TimeUnit.DAYS, linkedBlockingQueue,
				new ThreadPoolExecutor.CallerRunsPolicy());
		String content = null;
		connectionWork = new ConnectionWork();
		threadPool.execute(Thread.currentThread());
		ArrayList<Integer> idList = getVideoId(Url.courseUrl);
		videoPath = DataClass.videoPath.replace("path", Url.courseUrl.split("=")[1]);
		for (int i = 0; i < idList.size(); i++) {

			try {
				content = getContent(Url.mooc_url.replace("number", idList.get(i) + ""));
			} catch (IOException e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
			}
			if (content != null)
			{
				door_MoocVideo(content,idList.get(i));
			}

		}
		threadPool.shutdown();
	}

	/**
	 * 获取慕课视频的入口，直接调用即可
	 */
	public static void door_MoocVideo(String content,int baseId) {
		// 整一章的名字
		String htmlName1 = getHtmlName(replaceBlank(content));
		// createHtml(fixDir(htmlName1), content);
		content = replaceBlank(content);
		ArrayList<String> urlList = getVideoIdUrl(content,
				PatternString.patternHtmlUrl, Url.moocHost);
		Thread.currentThread().setPriority(8);
		// 创建文件夹
		createDir(htmlName1);
		for (int i = 0; i < urlList.size(); i++) {
			String[] arr = getVideoUrl(Url.videoAjax
					+ getIdFromUrl(urlList.get(i)));
			// 视频的名字
			String videoName = i + 1 + "、" + fixDir(arr[0]) + ".mp4";
			// 视频的url	
			String videoUrl = arr[1];
			String path = videoPath + htmlName1 + "/";
			CreateVideo videoCreate = new CreateVideo();
			videoCreate.setVideo(new Video(videoName, videoUrl, path, urlList
					.get(i)));
			videoCreate.setThreadPool(threadPool);
			Thread thread = new Thread(videoCreate, videoName + "下载线程!");
			int sizePool = threadPool.getPoolSize();
			// 只要线程池中的线程达到最大值，遍将线程强硬性放进队列
			if (sizePool == maximumPoolSize) {
				try {
					linkedBlockingQueue.put(thread);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
//					e.printStackTrace();
				}
			} else
				threadPool.execute(thread);
		}
	}
	// 获取视频链接
	@SuppressWarnings("static-access")
	public static String[] getVideoUrl(String url) {

		HttpURLConnection conn = connectionWork
				.getConn(url, new Url().moocHost);
		BufferedReader in = null;
		String result = "";
		try {
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
//			e1.printStackTrace();
		}
		String line;
		try {
			while ((line = in.readLine()) != null) {
				result += "\n" + line;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		JSONObject object = new JSONObject().fromObject(result);
		JSONObject object2 = new JSONObject().fromObject(object
				.getString("data"));
		JSONObject object3 = new JSONObject().fromObject(object2
				.getString("result"));
		JSONArray object4 = new JSONArray().fromObject(object3
				.getString("mpath"));
		String videoName = object3.getString("name");
		// String videoUrl = object4.get(0).toString();

		String urlL = "";
		String urlM = "";
		String urlH = "";
		for (int i = 0; i < object4.size(); ++i) {
			if ((object4.get(i).toString()).contains("/H.mp4")) {
				urlH = object4.get(i).toString();
			} else if ((object4.get(i).toString()).contains("/M.mp4")) {
				urlM = object4.get(i).toString();
			} else if ((object4.get(i).toString()).contains("/L.mp4")) {
				urlL = object4.get(i).toString();
			}
		}

		String videoUrl = null;
		if (!urlH.equals("")) {
			videoUrl = urlH;
		} else if (!urlM.equals("")) {
			videoUrl = urlM;
		} else if (!urlL.equals("")) {
			videoUrl = urlL;
		}

		return new String[] { videoName.replace("/", ""), videoUrl };
	}

	// 从包含id的链接中获取id
	public static String getIdFromUrl(String videoUrlId) {
		return videoUrlId.split("/")[4];
	}

	// 去掉空格、回车等特殊字符
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	// 获取网页内容
	public static String getContent(String htmlUrl) throws IOException {

		// 存储网页内容
		String contentData = "";
		// 通过url获取URL对象
		HttpURLConnection conn = null;
		conn = (HttpURLConnection) connectionWork.getConn(htmlUrl,Url.moocHost);
		InputStream inputStream = null;
		// 得到输入流
		try {
			inputStream = conn.getInputStream();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
//			e1.printStackTrace();
		}
		// 打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。
		BufferedInputStream reader = null;
		reader = new BufferedInputStream(new BufferedInputStream(inputStream));
		byte[] data = new byte[1024];
		try {
			while (reader.read(data) != -1) {
				contentData += new String(data, "utf-8");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		try {
			reader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		return contentData;
	}

	// 获取章节名字
	public static String getHtmlName(String contentData) {
		String patternString = PatternString.patternHtmlName;
		Pattern pattern = Pattern.compile(patternString,
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(contentData);
		String htmlName = "";
		while (matcher.find()) {
			htmlName = matcher.group();
		}
		return htmlName.substring(7, htmlName.length() - 8);
	}

	// 生成网页保存在 new Url().filePath；
	@SuppressWarnings("resource")
	public static boolean createHtml(String htmlName, String contentData) {
		String filePath = Url.filePath;
		File file = new File(filePath + htmlName + ".txt");
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(file);
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		try {
			fileWriter.write(contentData);
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		return true;
	}

	// 匹配符合的视频链接
	public static ArrayList<String> getVideoIdUrl(String contentData,
			String patternString, String addWord) {
		ArrayList<String> list = new ArrayList<String>();
		Pattern pattern = Pattern.compile(patternString,
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(contentData);
		while (matcher.find()) {
			String videoUrl = addWord + matcher.group().toString();
			if (!list.contains(videoUrl))
				list.add(addWord + matcher.group().toString());
		}
		return list;
	}

	// 获取视频內容的所有id
	public static ArrayList<Integer> getVideoId(String url) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		String content = null;
		try {
			content = getContent(url);
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		Pattern pattern = Pattern.compile(PatternString.patternStringVideoId,
				Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(replaceBlank(content));
		int max = 1;
		while (matcher.find()) {
			int path = Integer
					.parseInt(matcher.group().toString().split("=")[1]);
			if (max < path) {
				max = path;
			}
		}
		for (int i = 1; i <= max; i++) {
			try {
				content = getContent(url + "&page=" + i);
			} catch (IOException e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
			}
			pattern = Pattern.compile(PatternString.patternStringVideoId2,
					Pattern.CASE_INSENSITIVE);
			matcher = pattern.matcher(replaceBlank(content));
			while (matcher.find()) {
				int videoIndex = Integer.parseInt(matcher.group().toString()
						.split("/")[2]);
				if (!list.contains(videoIndex)) {
					list.add(videoIndex);
				}
			}
		}
		return list;
	}

	// 创建路径，传过来的参数为 xxx/xxx/xxx
	public static void createDir(String htmlName) {

		String path = videoPath + htmlName + "/";
		path = fixDir(path);
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
	}

	// 将传过来的字符串修改为符合文件夹以及文件的命名格式
	public static String fixDir(String dirName) {
		dirName = dirName.replace(":", "：");
		dirName = dirName.replace("\\", "");
		dirName = dirName.replace("*", "");
		dirName = dirName.replace("?", "");
		dirName = dirName.replace("'", "");
		dirName = dirName.replace("<", "");
		dirName = dirName.replace(">", "");
		dirName = dirName.replace("|", "");
		return dirName;
	}
}
